﻿using System.Linq.Extensions;
using System.Linq.PageList;
using Dyao.Repository.Abstractions;
using Dyao.Book.Contract;
using Dyao.Book.Entity;
using Dyao.Book.Repository;

namespace Dyao.Book.Repository
{
    using Foundation.Replacement;

    public class TaskCenterRecordViewRepository : DataViewRepository<TaskCenterRecordKeylessEntity>, ITaskCenterRecordViewRepository
    {
        /// <summary>
        /// 获取任务记录
        /// </summary>
        /// <param name="pageFilter">pageFilter</param>
        /// <param name="cancellationToken">cancellationToken</param>
        /// <returns></returns>
        public async Task<PageList<TaskCenterRecordKeylessEntity>> GetTaskCenterRecordModelPagedListAsync(IPageFilter<TaskCenterRecordFilterDto, TaskCenterRecordOrderByDto> pageFilter, CancellationToken cancellationToken = default)
        {
            var filter = pageFilter.Filter;
            var orderBy = pageFilter.OrderBy;
            var taskSetting = DbContext.Set<TaskCenterSettingsEntity>().AsQueryable();
            var queryable = DbContext.Set<TaskCenterRecordEntity>()
                                            .AsQueryable()
                                            .OrderOrThenBy(m => m.ID, orderBy.Id)
                                            .WhereIf(m => m.Category == filter.TaskCenterCategory, filter.TaskCenterCategory.HasValue)
                                            .WhereIf(m => m.CreateUserId == filter.UserId, filter.UserId.HasValue);
            if (filter.TaskSettingsIdList != null && filter.TaskSettingsIdList.Any())
            {
                queryable = queryable.Where(m => filter.TaskSettingsIdList.Contains(m.TaskCenterSettingsId) || m.MenuPath.Contains(filter.SearchText));
            }
            else
            {
                queryable = queryable.WhereIf(m => m.MenuPath.Contains(filter.SearchText), !string.IsNullOrWhiteSpace(filter.SearchText));
            }

            var queryableModel = queryable.Join(taskSetting, m => m.TaskCenterSettingsId, n => n.ID, (m, n) =>
            new TaskCenterRecordKeylessEntity()
            {
                Id = m.ID,
                Category = m.Category,
                TaskCenterSettingsName = n.DisplayName,
                TaskCenterSettingsId = m.TaskCenterSettingsId,
                Status = m.Status,
                MenuPath = m.MenuPath,
                ExcuteBeginDatetime = m.ExcuteBeginDatetime,
                ExcuteEndDatetime = m.ExcuteEndDatetime,
                ResultMessage = m.ResultMessage,
                CreateDateTime = m.CreateDateTime
            }).OrderOrThenBy(t => t.Id, false);

            var pageList = await queryableModel.ToPageListAsync(pageFilter, cancellationToken);
            return pageList;
        }
    }
}
